//
//  LoginViewController.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/8/11.
//

import UIKit
import Alamofire

class LoginViewController: BaseViewController {
    
    var onLogin: (() -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        initializeSubviews()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touchPoint = touches.first?.location(in: view) else { return }
        guard !phoneTextField.frame.contains(touchPoint), !codeTextField.frame.contains(touchPoint) else { return }
        view.endEditing(true)
    }
    
    private lazy var tLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.text = "手机号登录"
        v.font = UIFont.systemFont(ofSize: 30, weight: .bold)
        return v
    }()
    
    private lazy var descLabel: UILabel = {
        let v = UILabel()
        v.textColor = .black
        v.text = "未注册的手机号登陆成功后将自动注册"
        v.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        return v
    }()
    
    private lazy var phoneView: UIView = {
        let v = UIView()
        v.layer.cornerRadius = 5
        v.layer.masksToBounds = true
        v.layer.borderColor = UIColor(0xE9E9EA).cgColor
        v.layer.borderWidth = 1.0
        return v
    }()
    
    private lazy var phoneLabel: UILabel = {
        let v = UILabel()
        v.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        v.textColor = .black
        v.text = "+86"
        return v
    }()
    
    private lazy var phoneTextField: UITextField = {
        let v = UITextField()
        v.keyboardType = .numberPad
        v.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        v.textColor = .black
        v.attributedPlaceholder = NSAttributedString(string: "请输入手机号", attributes: [.foregroundColor: UIColor.darkGray])
        v.textAlignment = .right
        return v
    }()
    
    private lazy var codeView: UIView = {
        let v = UIView()
        v.layer.cornerRadius = 5
        v.layer.masksToBounds = true
        v.layer.borderColor = UIColor(0xE9E9EA).cgColor
        v.layer.borderWidth = 1.0
        return v
    }()
    
    private lazy var codeTextField: UITextField = {
        let v = UITextField()
        v.keyboardType = .numberPad
        v.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        v.textColor = .black
        v.attributedPlaceholder = NSAttributedString(string: "请输入验证码", attributes: [.foregroundColor: UIColor.darkGray])
        v.textAlignment = .left
        return v
    }()
    
    private lazy var codeButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("获取验证码", for: .normal)
        v.setTitleColor(UIColor.black, for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        v.addTarget(self, action: #selector(onClickGetCodeButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var codeLabel: UILabel = {
        let v = UILabel()
        v.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        v.textColor = .black
        v.isHidden = true
        return v
    }()
    
    private lazy var submitButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("登陆", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: .highlighted)
        v.backgroundColor = UIColor(0xD3C390)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        v.addTarget(self, action: #selector(onClickSubmitButton(_:)), for: .touchUpInside)
        v.layer.cornerRadius = 5
        v.layer.masksToBounds = true
        return v
    }()
    
    private lazy var checkButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setImage(UIImage(resource: .checkNo), for: .normal)
        v.setImage(UIImage(resource: .checkYes), for: .selected)
        v.addTarget(self, action: #selector(onClickCheckButton(_:)), for: .touchUpInside)
        v.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 5)
        return v
    }()
    
    private lazy var checkDetailButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("我同意《用户协议》", for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
        v.setTitleColor(UIColor.black, for: .normal)
        v.addTarget(self, action: #selector(onClickCheckDetailButton(_:)), for: .touchUpInside)
        v.setTitleColor(UIColor.black.withAlphaComponent(0.6), for: .highlighted)
        return v
    }()
    
    private var timer: ZZTimer?
    
    private var timeCounter: Int = 60
    
    private var dataTask: URLSessionDataTask?
}

extension LoginViewController {
    
    private func initializeSubviews() {
        
        titleLabel.text = nil
        view.addSubview(tLabel)
        tLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(naviHeaderView.snp.bottom)
        }
        
        view.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(tLabel.snp.bottom).offset(10)
        }
        
        view.addSubview(phoneView)
        phoneView.snp.makeConstraints { make in
            make.top.equalTo(descLabel.snp.bottom).offset(40)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(50)
        }
        
        phoneView.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.centerY.equalToSuperview()
        }
        
        phoneView.addSubview(phoneTextField)
        phoneTextField.snp.makeConstraints { make in
            make.left.equalTo(phoneLabel.snp.right).offset(10)
            make.centerY.equalToSuperview()
            make.right.equalTo(-10)
        }
        
        view.addSubview(codeView)
        codeView.snp.makeConstraints { make in
            make.top.equalTo(phoneView.snp.bottom).offset(20)
            make.left.right.height.equalTo(phoneView)
        }
        
        codeView.addSubview(codeLabel)
        codeLabel.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
        }
        
        codeButton.sizeToFit()
        codeView.addSubview(codeButton)
        codeButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.width.equalTo(codeButton.frame.size.width)
        }
        
        codeView.addSubview(codeTextField)
        codeTextField.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.centerY.equalToSuperview()
            make.right.equalTo(codeButton.snp.left).offset(-10)
        }
        
        view.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.top.equalTo(codeView.snp.bottom).offset(30)
            make.left.right.height.equalTo(codeView)
        }
        
        let v = UIView()
        view.addSubview(v)
        v.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(submitButton.snp.bottom).offset(30)
        }
        
        v.addSubview(checkButton)
        checkButton.snp.makeConstraints { make in
            make.left.top.bottom.equalTo(0)
        }
        
        v.addSubview(checkDetailButton)
        checkDetailButton.snp.makeConstraints { make in
            make.left.equalTo(checkButton.snp.right)
            make.right.equalTo(-20)
            make.centerY.equalToSuperview()
        }
    }
    
    @objc private func onClickGetCodeButton(_ sender: UIButton) {
        view.endEditing(true)
        guard checkButton.isSelected else {
            Toast.show(message: "需同意用户协议")
            return
        }
        let phone = phoneTextField.text ?? ""
        guard !phone.isEmpty, phone.count == 11 else {
            Toast.show(message: "请输入正确的手机号")
            return
        }
        let urlStr = App.kSmsSend.absoluteString + "?phonenumber=\(phone)"
        guard let url = URL(string: urlStr) else {
            return
        }
        codeButton.isEnabled = false
        AF.request(url).response { [weak self] response in
            guard let `self` = self, let data = response.data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                self?.codeButton.isEnabled = true
                return
            }
            let code = json["code"] as? Int ?? -1
            if code == 200 {
                Toast.show(message: "验证码已发送")
                self.startTimer()
                self.codeButton.isEnabled = false
                self.codeButton.isHidden = true
                self.codeLabel.isHidden = false
            } else {
                self.codeButton.isEnabled = true
                self.codeButton.isHidden = false
                self.codeLabel.isHidden = true
                Toast.show(message: json["msg"] as? String ?? "发送失败")
            }
        }
    }
    
    @objc private func onClickSubmitButton(_ sender: UIButton) {
        view.endEditing(true)
        guard checkButton.isSelected else {
            Toast.show(message: "需同意用户协议")
            return
        }
        let phone = phoneTextField.text ?? ""
        guard !phone.isEmpty, phone.count == 11 else {
            Toast.show(message: "请输入正确的手机号")
            return
        }
        let code = codeTextField.text ?? ""
        guard !code.isEmpty else {
            Toast.show(message: "请输入验证码")
            return
        }
        let headers = [
            "Content-Type": "application/json"
        ]
        let parameters = [
            "phonenumber": phone,
            "smsCode": code
        ] as [String : Any]
        guard let postData = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
        self.submitButton.isEnabled = false
        let request = NSMutableURLRequest(url: App.kRegister,
                                                cachePolicy: .useProtocolCachePolicy,
                                            timeoutInterval: 30.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData as Data
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { [weak self] (data, response, error) -> Void in
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                self.submitButton.isEnabled = true
                self.stopTimer()
                if (error != nil) {
                    Toast.show(message: error?.localizedDescription ?? "网络异常")
                } else {
                    guard let data = data, let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                        Toast.show(message: "登陆失败")
                        return
                    }
                    let code = json["code"] as? Int ?? -1
                    print(json)
                    if code == 200 {
                        Toast.show(message: "登陆成功")
                        if let info = json["data"] as? [String: Any] {
                            App.shared.userName = info["accountName"] as? String
                            App.shared.userAvatar = info["avatar"] as? String
                        }
                        self.onLogin?()
                        self.navigationController?.popViewController(animated: true)
                    } else {
                        Toast.show(message: json["msg"] as? String ?? "登陆失败")
                    }
                }
            }
        })
        dataTask.resume()
        self.dataTask = dataTask
    }
    
    @objc private func onClickCheckButton(_ sender: UIButton) {
        view.endEditing(true)
        sender.isSelected = !sender.isSelected
    }
    
    @objc private func onClickCheckDetailButton(_ sender: UIButton) {
        view.endEditing(true)
        
    }
    
    private func startTimer() {
        timeCounter = 60
        timer?.pause()
        timer = nil
        let t = ZZTimer(.main)
        t.scheduled(repeat: 1, qos: .default) { [weak self] in
            self?.timerAction()
        }
        timer = t
        t.fire()
    }
    
    private func stopTimer() {
        timer?.pause()
        self.codeButton.isEnabled = true
        self.codeButton.isHidden = false
        self.codeLabel.isHidden = true
    }
    
    private func timerAction() {
        timeCounter -= 1
        if timeCounter <= 0 {
            self.codeLabel.text = nil
            self.stopTimer()
        } else {
            self.codeLabel.text = "\(timeCounter)s"
        }
    }
}


